using System.ServiceModel;
using Framework.Remoting.Conventions;

namespace Framework.Remoting.Client
{
    public class AutoManagedRequest : RequestBase
    {
        private ICommunicationObject currentChannel;

        public AutoManagedRequest(IChannelFactoryFactory channelFactoryFactory)
            : base(channelFactoryFactory)
        {
        }

        public override T BeginRequest<T>(WcfServiceInfo wcfServiceInfo)
        {
            if (currentChannel == null)
            {
                currentChannel = (ICommunicationObject) CreateChannel<T>(wcfServiceInfo);
            }
            else if (currentChannel.State != CommunicationState.Opened)
            {
                currentChannel = (ICommunicationObject) CreateChannel<T>(wcfServiceInfo);
            }

            return (T) currentChannel;
        }

        public override void EndRequest<T>(T channel)
        {
            ManageChannel(channel, false);
        }

        public override void Dispose()
        {
            ManageChannel(currentChannel, true);
        }
    }
}